package me.young.android.fullscreengesture

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.support.v7.preference.PreferenceManager
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.widget.Toast
import swipe.SwipeIndicator
import swipe.SwipeTouchView
import com.yhao.floatwindow.FloatWindow
import com.yhao.floatwindow.MoveType
import com.yhao.floatwindow.PermissionListener
import com.yhao.floatwindow.Screen

class FullScreenAccessService : AccessibilityService() {

    companion object {
        const val TAG_INDICATOR: String = "Indicator"
        const val TAG_TOUCH_L: String = "TouchL"
        const val TAG_TOUCH_R: String = "TouchR"
        var sInstance: FullScreenAccessService? = null
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        sInstance = this
        start()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        sInstance = null
        return super.onUnbind(intent)
    }

    private fun start() {
        val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
        val swipeIndicator = SwipeIndicator(this)
        val vibrateEnabled = sharedPref.getBoolean(SettingFragment.KEY_PREF_VIBRATE_ENABLED, true)
        val vibrateMills = sharedPref.getInt(SettingFragment.KEY_PREF_VIBRATE_MILLS, 50)
        FloatWindow
                .with(applicationContext)
                .setView(swipeIndicator)
                .setWidth(Screen.width, 1f)                               //设置控件宽高
                .setHeight(Screen.height, 1f)
                .setX(0)                                   //设置控件初始位置
                .setY(0)
                .setTouchable(false)
                .setMoveType(MoveType.fixed)
                .setTag(TAG_INDICATOR)
                .setDesktopShow(true)   //监听悬浮控件状态改变
                .setPermissionListener(object : PermissionListener {
                    override fun onFail() {
                        Toast.makeText(applicationContext, R.string.permission_failed, Toast.LENGTH_SHORT).show()
                    }

                    override fun onSuccess() {
                    }

                })  //监听权限申请结果
                .build()
        val leftEnabled = sharedPref.getBoolean(SettingFragment.KEY_PREF_LEFT_ENABLED, true)
        if (leftEnabled) {
            val leftWidth = sharedPref.getInt(SettingFragment.KEY_PREF_LEFT_WIDTH, 3)
            val swipeTouchView = SwipeTouchView(this, true, swipeIndicator, {
                back()
            }, {
                vibrate(vibrateEnabled, vibrateMills)
            })
            FloatWindow
                    .with(applicationContext)
                    .setView(swipeTouchView)
                    .setWidth(Screen.width, leftWidth.toFloat() / 100f)
                    .setHeight(Screen.height, 1f)
                    .setX(0)                                   //设置控件初始位置
                    .setY(0)
                    .setTag(TAG_TOUCH_L)
                    .setTouchable(true)
                    .setMoveType(MoveType.fixed)
                    .setDesktopShow(true)   //监听悬浮控件状态改变
                    .setPermissionListener(object : PermissionListener {
                        override fun onFail() {
                            Toast.makeText(applicationContext, R.string.permission_failed, Toast.LENGTH_SHORT).show()
                        }

                        override fun onSuccess() {
                        }

                    })  //监听权限申请结果
                    .build()
        }
        val rightEnabled = sharedPref.getBoolean(SettingFragment.KEY_PREF_RIGHT_ENABLED, true)
        if (rightEnabled) {
            val swipeTouchViewR = SwipeTouchView(this, true, swipeIndicator, {
                back()
            }, true, {
                vibrate(vibrateEnabled, vibrateMills)
            })
            val rightWidth = sharedPref.getInt(SettingFragment.KEY_PREF_RIGHT_WIDTH, 3)
            FloatWindow
                    .with(applicationContext)
                    .setView(swipeTouchViewR)
                    .setWidth(Screen.width, rightWidth.toFloat() / 100f)                               //设置控件宽高
                    .setHeight(Screen.height, 1f)
                    .setX(Screen.width, 0.97f)                                   //设置控件初始位置
                    .setY(0)
                    .setTag(TAG_TOUCH_R)
                    .setTouchable(true)
                    .setMoveType(MoveType.fixed)
                    .setDesktopShow(true)   //监听悬浮控件状态改变
                    .setPermissionListener(object : PermissionListener {
                        override fun onFail() {
                            Toast.makeText(applicationContext, R.string.permission_failed, Toast.LENGTH_SHORT).show()
                        }

                        override fun onSuccess() {
                        }

                    })  //监听权限申请结果
                    .build()
        }
    }

    private fun vibrate(vibrateEnabled: Boolean, vibrateMills: Int) {
        if (vibrateEnabled) {
            val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(vibrateMills.toLong(), VibrationEffect.DEFAULT_AMPLITUDE))
            }
        }
    }

    override fun onInterrupt() {
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
    }

    private fun back() {
        performGlobalAction(GLOBAL_ACTION_BACK)
    }

    fun reset() {
        Log.d("test", "test")
        FloatWindow.destroy(TAG_INDICATOR)
        FloatWindow.destroy(TAG_TOUCH_L)
        FloatWindow.destroy(TAG_TOUCH_R)
        start()
    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        if (newConfig!!.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            FloatWindow.destroy(TAG_INDICATOR)
            FloatWindow.destroy(TAG_TOUCH_L)
            FloatWindow.destroy(TAG_TOUCH_R)
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            start()
        }
    }

}